<?php

class Account_Model_Auth
{
	const ACCOUNT_NOT_FOUND = 'accountNotFound';
	const ACCOUNT_INACTIVE = 'accountInactive';
	const PASSWORDS_MISMATCH = 'passwordsMismatch';


	protected $_authErrorCode = null;


	public function authenticate($identity = null, $password = null)
	{
		if (empty($identity)) {
			throw new Exception('Empty identity');
		}


		$key = 'idname';
		// Check if the input is a valid email address
		$emailAddressValidator = new Zend_Validate_EmailAddress();
		if ($emailAddressValidator->isValid($identity)) {
			$key = 'email';
		}


		$accountTbl = Account_Model_DbTable_Account::getInstance();

		$select = $accountTbl->select();
		$select->where($key .'= ?', $identity);

		$accountDbRes = $accountTbl->fetchAll($select);

		if ($accountDbRes->count() !== 1) {
			$this->_authErrorCode = self::ACCOUNT_NOT_FOUND;
			return NULL;
		}


		$accountDbRow = $accountDbRes->getRow(0);
		$accountId = $accountDbRow->id;


		$statusTbl = Account_Model_DbTable_Status::getInstance();

		$select = $statusTbl->select();
		$select->where('account_id= ?', $accountId);

		$statusDbRes = $statusTbl->fetchAll($select);

		$statuses = array();
		foreach ($statusDbRes as $statusDbRow) {
			$statuses[] = $statusDbRow->status;
		}

		//TODO: move into AccountStatus
		if (in_array('pending', $statuses) || in_array('suspended', $statuses) || in_array('banned', $statuses)) {
			$this->_authErrorCode = self::ACCOUNT_INACTIVE;
			return NULL;
		}


		if (md5($accountDbRow->salt . sha1($password)) != $accountDbRow->passkey) {
			$this->_authErrorCode = self::PASSWORDS_MISMATCH;
			return NULL;
		}

		//CHECK: put session init here?
		return $accountDbRow->id;
	}

	public function getErrorCode()
	{
		return $this->_authErrorCode;
	}
}